﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Convo;
using Hawaii.Services.Client.Relay;
using Hawaii.Services.Client;
using System.Threading;
using System.Text;
using Convo.POCOs;
using System.Windows.Media.Imaging;
using Coding4Fun.Phone.Controls;
using ServiceMessages.ResponsePOCOs;

namespace Convo
{
    public partial class LoginPage : PhoneApplicationPage
    {
        private ConvoClient client;
        public LoginPage()
        {
            InitializeComponent();
            client = new ConvoClient("http://127.0.0.1:81/Service1.svc");
        }

        private RelayContext RelayContext
        {
            get { return ((App)App.Current).RelayContext; }
        }

        private void loginBtn_Click(object sender, RoutedEventArgs e)
        {
            var request = client.loginRequest(emailTxtBox.Text, passwordTxtBox.Password);

            client.ExecuteAsync<LoginResponse>(request, (response) =>
            {
                LoginResponse user = response.Data;

                
                if (response.StatusCode == HttpStatusCode.OK && user != null)
                {
                    (App.Current as App).User = user;
                    RelayService.CreateEndPointAsync(HawaiiClient.HawaiiApplicationId, "Convo", this.OnCompleteCreateEndPoint);
                    this.NavigationService.Navigate(new Uri("/ChatFriends.xaml", UriKind.Relative));
                }
                else
                {
                    MessageBox.Show("Could not log in. Please check email/password and try again.");
                }
            });
        }

        private void newAccountBtn_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/AddAccountPage.xaml", UriKind.Relative));
        }

        private void OnCompleteCreateEndPoint(EndpointResult result)
        {
            if (result.Status == Status.Success)
            {
                // Set the newly created endpoint available in result as active(my) endpoint.

                this.RelayContext.Endpoint = result.EndPoint;

                (App.Current as App).ConvContext = new ConvId();

                Thread outputThread = new Thread(new ThreadStart(receiveMessages));
                outputThread.Start();
                while (!outputThread.IsAlive) ;
            }
        }

        private void receiveMessages()
        {
            while (true)
            {
                RelayService.ReceiveMessagesAsync(HawaiiClient.HawaiiApplicationId, this.RelayContext.Endpoint, string.Empty, this.ReceiveMessages);

                Thread.Sleep(5000);
            }
        }

        private void ReceiveMessages(MessagingResult result)
        {

            if (result.Status == Status.Success)
            {
                if (result.Messages != null && result.Messages.Count != 0)
                {
                    
                    foreach (Message message in result.Messages)
                    {
                        
                        this.RelayContext.Messages.Add(message);

                        if (message.From.Equals((App.Current as App).ConvContext.Endpoint))
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>      //this will async. execute in UI
                            { (App.Current as App).ChatRef.textBox2.Text = Encoding.Unicode.GetString(message.Body, 0, message.Body.Length); });
                        }
                        else
                        {
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                var messagePrompt = new MessagePrompt
                                {
                                    Title = "Simple Message",
                                    Message = "You have a message from..."

                                };
                                //messagePrompt.Completed += messagePrompt_Completed;
                                messagePrompt.Show();
                            });
                            
                        }
                    }
                }
            }
        }

    }
}